package com.xvjialing.lytech.weatherreport.net;

import com.alibaba.fastjson.JSON;
import com.xvjialing.lytech.weatherreport.bean.WeatherData;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class WeatherDataServiceImpl implements WeatherDataService{

    private Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);

    @Value("${weather.cityurl}")
    private String cityUrl;

    @Value("${weather.citykeyurl}")
    private String citykeyurl;

    @Value("${spring.redis.avalible-time}")
    private long avalibleTime;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public WeatherData getWeatherDataByCityCode(String cityCode){
        return getWeatherData(citykeyurl+ cityCode);
    }

    @Override
    public WeatherData getWeatherDataByCityName(String cityName){
        return getWeatherData(cityUrl+cityName);
    }

    @Override
    public void syncWeatherByCityName(String cityName) {
        saveWeatherData(cityUrl+cityName);
    }

    @Override
    public void syncWeatherByCityCode(String cityCode) {
        saveWeatherData(citykeyurl+cityCode);
    }

    public WeatherData getWeatherData(String url) {
        Response response =null;
        String strBody=null;
        WeatherData weatherData=null;

        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        //先查缓存，缓存中有的取缓存中的数据
        if (stringRedisTemplate.hasKey(url)){
            strBody=operations.get(url);
            logger.info("fromRedis");

        }else {
            //缓存没有，再调用服务接口
            OkHttpClient okHttpClient=new OkHttpClient();
            Request request=new Request.Builder()
                    .url(url)
                    .build();
            try {
                response = okHttpClient.newCall(request).execute();
            }catch (Exception e){
                e.printStackTrace();
            }
            if (response.isSuccessful()){
                try {
                    strBody=response.body().string();
                    //数据写入缓存
                    operations.set(url,strBody,avalibleTime, TimeUnit.SECONDS);  //avalibleTime为数据有效时间，超出这个时间数据就自动销毁

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            logger.info("fromNet");
        }
        weatherData= JSON.parseObject(strBody,WeatherData.class);
        return weatherData;
    }

    public void saveWeatherData(String url){
        Response response =null;

        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder()
                .url(url)
                .build();
        try {
            response = okHttpClient.newCall(request).execute();
        }catch (Exception e){
            e.printStackTrace();
        }
        if (response.isSuccessful()){
            try {
                String body = response.body().string();
                WeatherData weatherData = JSON.parseObject(body, WeatherData.class);
                if (weatherData.getStatus()==1000){
                    //数据写入缓存
                    operations.set(url,body,avalibleTime, TimeUnit.SECONDS);  //avalibleTime为数据有效时间，超出这个时间数据就自动销毁
                    logger.info("body:{}",body);
                }else {
                    logger.info("body:{}",body+";"+url);
                }
                
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}